<template>
	<div class="layout-padding">
		<splitpanes>
			<pane size="20">
				<div class="layout-padding-auto layout-padding-view">
					<el-input prefix-icon="search" v-model="filterText" placeholder="请输入关键字搜索" class="mb-2" />
					<el-scrollbar>
						<el-tree
							ref="treeRef"
							:data="treeData.list"
							:props="treeData.defaultProps"
							@node-click="handleNodeClick"
							node-key="id"
							:default-expand-all="true"
							:highlight-current="true"
							:expand-on-click-node="false"
							:filter-node-method="filterNode"
						/>
					</el-scrollbar>
				</div>
			</pane>
			<pane class="ml8">
				<div class="layout-padding-auto layout-padding-view">
					<el-row>
						<el-form :model="form" ref="dataFormRef" :inline="true" @keyup.enter="getDataList" :rules="dataRules" v-loading="loading">
							<el-form-item label="数据类型" prop="range">
								<el-radio-group v-model="form.range" size="small" @change="toggleRange" class="!flex-nowrap">
									<el-radio-button v-for="item in trandRangeTime" :key="item.name" :label="item.name">
										{{ item.label }}
									</el-radio-button>
								</el-radio-group>
							</el-form-item>
							<el-form-item label="时间" prop="dateTime" class="w-[180px]">
								<el-date-picker
									size="small"
									v-model="form.dateTime"
									:type="form.range === 'DailyAvg' ? 'date' : 'month'"
									start-placeholder="开始时间"
									end-placeholder="结束时间"
									@change="handleDateChange"
									value-format="YYYY-MM-DD"
								/>
							</el-form-item>
							<el-form-item prop="deviceId" label="设备">
								<el-select placeholder="请选择设备" v-model="form.deviceId" size="small" filterable @change="getDataList()">
									<el-option v-for="item in deviceList" :key="item.id" :value="item.id" :label="item.name" />
								</el-select>
							</el-form-item>
							<el-form-item>
								<el-button icon="search" type="primary" class="ml-2" size="small" @click="getDataList">查询</el-button>
							</el-form-item>
						</el-form>
					</el-row>
					<div class="h-[calc(100%-60px)] overflow-y-auto px-2">
						<el-collapse v-model="activeNames" @change="handleCollapse">
							<el-collapse-item name="1">
								<template #title>
									<span class="text-primary">空气质量指数</span>
								</template>
								<el-card>
									<div class="w-full h-[240px]">
										<TrendChart
											:current="chartData.current"
											:previous="chartData.previous"
											:growthRate="chartData.growthRate"
											deviser="aqi"
											:loading="loading"
											ref="TrendChart1Ref"
										/>
									</div>
								</el-card>
							</el-collapse-item>
							<el-collapse-item name="2">
								<template #title>
									<span class="text-primary">一氧化碳</span>
									<span class="pl-2 text-info">(mg/m³)</span>
								</template>
								<el-card>
									<div class="w-full h-[240px]">
										<TrendChart
											:current="chartData.current"
											:previous="chartData.previous"
											:growthRate="chartData.growthRate"
											deviser="co"
											:loading="loading"
											ref="TrendChart2Ref"
										/>
									</div>
								</el-card>
							</el-collapse-item>
							<el-collapse-item name="3">
								<template #title>
									<span class="text-primary">臭氧</span>
									<span class="pl-2 text-info">(μg/m³)</span>
								</template>
								<el-card>
									<div class="w-full h-[240px]">
										<TrendChart
											:current="chartData.current"
											:previous="chartData.previous"
											:growthRate="chartData.growthRate"
											deviser="o3"
											:loading="loading"
											ref="TrendChart3Ref"
										/>
									</div>
								</el-card>
							</el-collapse-item>
							<el-collapse-item name="4">
								<template #title>
									<span class="text-primary">二氧化硫</span>
									<span class="pl-2 text-info">(μg/m³)</span>
								</template>
								<el-card>
									<div class="w-full h-[240px]">
										<TrendChart
											:current="chartData.current"
											:previous="chartData.previous"
											:growthRate="chartData.growthRate"
											deviser="so2"
											:loading="loading"
											ref="TrendChart4Ref"
										/>
									</div>
								</el-card>
							</el-collapse-item>
							<el-collapse-item name="5">
								<template #title>
									<span class="text-primary">二氧化氮</span>
									<span class="pl-2 text-info">(μg/m³)</span>
								</template>
								<el-card>
									<div class="w-full h-[240px]">
										<TrendChart
											:current="chartData.current"
											:previous="chartData.previous"
											:growthRate="chartData.growthRate"
											deviser="no2"
											:loading="loading"
											ref="TrendChart5Ref"
										/>
									</div>
								</el-card>
							</el-collapse-item>
							<el-collapse-item name="6">
								<template #title>
									<span class="text-primary">细颗粒物(PM2.5)</span>
									<span class="pl-2 text-info">(μg/m³)</span>
								</template>
								<el-card>
									<div class="w-full h-[240px]">
										<TrendChart
											:current="chartData.current"
											:previous="chartData.previous"
											:growthRate="chartData.growthRate"
											deviser="pm25"
											:loading="loading"
											ref="TrendChart6Ref"
										/>
									</div>
								</el-card>
							</el-collapse-item>
							<el-collapse-item name="7">
								<template #title>
									<span class="text-primary">颗粒物(PM10)</span>
									<span class="pl-2 text-info">(μg/m³)</span>
								</template>
								<el-card>
									<div class="w-full h-[240px]">
										<TrendChart
											:current="chartData.current"
											:previous="chartData.previous"
											:growthRate="chartData.growthRate"
											deviser="pm10"
											:loading="loading"
											ref="TrendChart7Ref"
										/>
									</div>
								</el-card>
							</el-collapse-item>
						</el-collapse>
					</div>
				</div>
			</pane>
		</splitpanes>
	</div>
</template>

<script setup lang="ts" name="YOYAnalysis">
import { fetchYoyList as fetchList } from '/@/api/platform/trendAnalysis';
import { fetchAreaList as fetchTreeList } from '/@/api/platform/codeArea';
import { handleTree } from '/@/utils/other';
import { fetchListByTag } from '/@/api/platform/airMonitorEquipment';
import { trandRangeTime } from './data';
import { useMessage } from '/@/hooks/message';
import { formatDate } from '/@/utils/formatTime';
const TrendChart = defineAsyncComponent(() => import('../sequentialAnalysis/components/trendChart.vue'));
type Tree = {
	[key: string]: any;
};
type optionType = {
	id: string;
	name: string;
};
const activeNames = ref(['1', '2', '3', '4', '5', '6', '7']);
const siteId = ref<string>();
const filterText = ref('');
const loading = ref(true);
const dataFormRef = ref();
const deviceList = ref<optionType[]>([]);

const form = reactive({
	range: trandRangeTime[0].name,
	deviceId: '',
	dateTime: formatDate(new Date(), 'YYYY-mm-dd'),
});
// 定义校验规则
const dataRules = ref({
	range: [{ required: true, message: '请选择', trigger: 'change' }],
	deviceId: [{ required: true, message: '请选择', trigger: 'change' }],
	dateTime: [{ required: true, message: '请选择', trigger: 'change' }],
});
// 定义变量内容
const chartData = reactive({
	current: [], //本期
	growthRate: [], //增长率
	previous: [], //上期
});
const treeRef = ref();
const TrendChart1Ref = ref();
const TrendChart2Ref = ref();
const TrendChart3Ref = ref();
const TrendChart4Ref = ref();
const TrendChart5Ref = ref();
const TrendChart6Ref = ref();
const TrendChart7Ref = ref();

// 区域树使用的数据
const treeData = reactive({
	list: [],
	defaultProps: {
		label: 'name',
	},
});
// 点击树
const handleNodeClick = (e: any) => {
	siteId.value = e.id;
	getDeviceList();
};
// 搜索树监听
watch(filterText, (val) => {
	treeRef.value!.filter(val);
});
const filterNode = (value: string, data: Tree) => {
	if (!value) return true;
	return data.name.includes(value);
};

// 树节点查找设备
const getDeviceList = () => {
	fetchListByTag({ tag: unref(siteId) }).then((res) => {
		deviceList.value = res.data;
		form.deviceId = '';
	});
};
// 树节点查找设备
const getTreeDate = async () => {
	await fetchTreeList().then((res: any) => {
		const records = res.data;
		if (records.length) {
			treeData.list = handleTree(records, 'id', 'pid', 'children', '1111111111111111111');
			siteId.value = treeData.list[0]?.id;
			getDeviceList();
			nextTick(() => {
				unref(treeRef)?.setCurrentKey(siteId.value, true);
			});
		}
	});
};

const getDataList = async () => {
	const valid = await dataFormRef.value.validate().catch(() => {});
	if (!valid) return false;
	try {
		loading.value = true;
		const res = await fetchList({ dt0: form.dateTime, tp: form.range, monitorEquipmentId: form.deviceId });
		chartData.current = res.data?.current || [];
		chartData.growthRate = res.data?.growthRate || [];
		chartData.previous = res.data?.previous || [];
	} catch (err: any) {
		useMessage().error(err.msg || '请求错误');
	} finally {
		loading.value = false;
	}
};
const toggleRange = () => {
	getDataList();
};
const handleDateChange = () => {
	getDataList();
};
onMounted(() => {
	getTreeDate();
	setTimeout(() => {
		loading.value = false;
	}, 200);
});
const handleCollapse = () => {
	nextTick(() => {
		unref(TrendChart1Ref).resize();
		unref(TrendChart2Ref).resize();
		unref(TrendChart3Ref).resize();
		unref(TrendChart4Ref).resize();
		unref(TrendChart5Ref).resize();
		unref(TrendChart6Ref).resize();
		unref(TrendChart7Ref).resize();
	});
};
</script>
